package com.android.tabtestpack;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.android.R;
import com.android.displayscreen.MyScreenDisplay;
import com.android.displayscreen.MyScreenDisplayAdapter;
import com.android.displayscreen.MyScreenLayout;

public class Inbox extends Activity implements Runnable,View.OnClickListener{
	/** Called when the activity is first created. */

	EditText userName;
	EditText password;
	private ProgressDialog pd ;
//	ArrayAdapter<String> aa;
	ListView listItems;
	ArrayList<String> getlist;
	String concat;
	//TableLayout tl;
	ArrayList<ArrayList<String>> dataFromDataBase;
	//TableRow tr[] = new TableRow[dataFromDataBase.size()];/* Create a array of TableRow */
	//TextView [] textViews = new TextView[dataFromDataBase.size()*4];/* Create a array of TextView */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox);
	//	tl = (TableLayout)findViewById(R.id.myTableLayout);
		pd = ProgressDialog.show(this, "Please Wait..", "Getting results..", true,false);
		listItems=(ListView)findViewById(R.id.listItems);
		getlist = new ArrayList<String>();
		dataFromDataBase = new ArrayList<ArrayList<String>>();
		listItems.setBackgroundColor(Color.GRAY);
//		aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getlist);
 //       listItems.setAdapter(aa);
		Thread thread = new Thread(this);
		thread.start();
		
	}



	public void run() {
		try {
			
			Looper.prepare();

/*			HashMap<String,String> data= new HashMap<String, String>();
			data.put("action","retrieve_incoming_fax_list");
			//	data.put("username",userName.getText().toString());
			data.put("username","mtcsindia@gmail.com");
			//		data.put("password",password.getText().toString());
			data.put("password","5znavqps");
			data.put("dateFrom","2010-04-13 01:00:00");
			data.put("dateTo","2010-04-15 23:00:00");

			InputStream toastData= (doSubmit("https://api.popfax.com/api-server.php", data));

	*/		/* Get a SAXParser from the SAXPArserFactory. */ 
/*			SAXParserFactory spf = SAXParserFactory.newInstance(); 
			SAXParser sp = spf.newSAXParser(); 

*/			/* Get the XMLReader of the SAXParser we created. */ 
//			XMLReader xr = sp.getXMLReader(); 
			/* Create a new ContentHandler and apply it to the XML-Reader*/ 
//			ExampleHandler myExampleHandler = new ExampleHandler(); 
//			xr.setContentHandler(myExampleHandler); 

			/* Parse the xml-data from our URL. */ 
//			xr.parse(new InputSource(toastData)); 
			/* Parsing has finished. */ 

			/* Our ExampleHandler now provides the parsed data to us. */ 
//			ParsedExampleDataSet parsedExampleDataSet = 
//				myExampleHandler.getParsedData(); 
			/*Get data from ParsedExampleDataSet in HashMap*/
			
//			dataFromDataBase = parsedExampleDataSet.getRowWiseData();
			/* Set the result to be displayed in our GUI. */
			ArrayList <String>  extractedString = new ArrayList<String>();
			extractedString.add("123456");
			extractedString.add("himanshu");
			extractedString.add("10-12-86");
			extractedString.add("2");
			dataFromDataBase.add(extractedString);
			ArrayList <String> extractedString1 = new ArrayList<String>();
			extractedString1.add("654321");
			extractedString1.add("deepak");
			extractedString1.add("10-12-96");
			extractedString1.add("1");
			dataFromDataBase.add(extractedString1);
			System.out.println(dataFromDataBase.get(0));
			System.out.println(dataFromDataBase.get(1));
			System.out.println(dataFromDataBase.size());
			MyScreenLayout myscreenlayout = new MyScreenLayout(this);
			myscreenlayout.setlayout(dataFromDataBase.get(0));

//			setListAdapter(myscreendisplay);
//			TableRow tr[] = new TableRow[dataFromDataBase.size()+1];/* Create a array of TableRow */
//			TextView [] textViews = new TextView[dataFromDataBase.size()*4 ];/* Create a array of TextView */
	        /* Find Tablelayout defined in main.xml */ 
/*			textViews[0] = new TextView(this);
            textViews[0].setText("FROM");
            textViews[0].setWidth(100);
            textViews[1] = new TextView(this);
            textViews[1].setText("PAGES");
            textViews[1].setWidth(100);
            textViews[2] = new TextView(this);
            textViews[2].setText("DATE-TIME");
            textViews[2].setWidth(100);
            tr[0]=new TableRow(this);
            tr[0].addView(textViews[0]);
            tr[0].addView(textViews[1]);
            tr[0].addView(textViews[2]);
            tr[0].setFocusable(true);
            tr[0].setFocusableInTouchMode(true);
         
             
            tr[0].setOnClickListener(this);
            
            tl.addView(tr[0]);
*/		
/*	             for(int i=0;i<dataFromDataBase.size();i++)
	             {
	
           textViews[i+1] = new TextView(this);
	             textViews[i+1].setText(dataFromDataBase.get(i).get(1));
	             textViews[i+1].setWidth(80);
	             textViews[i+2] = new TextView(this);
	             textViews[i+2].setText(dataFromDataBase.get(i).get(3));
	             textViews[i+2].setWidth(80);
	             textViews[i+3] = new TextView(this);
	             textViews[i+3].setText(dataFromDataBase.get(i).get(2));
	               tr[i+1]=new TableRow(this);
	               tr[i+1].addView(textViews[i+1]);
	               tr[i+1].addView(textViews[i+2]);
	               tr[i+1].addView(textViews[i+3]);
	              
	             tr[i+1].setFocusable(true);
	             tr[i+1].setFocusableInTouchMode(true);
	          
	             
	             tr[i+1].setOnClickListener(this);
	            
	             tl.addView(tr[i+1]); 
	            	 concat= new String();
	            	 concat= dataFromDataBase.get(i).get(1) + "   " + dataFromDataBase.get(i).get(3) +"   " + dataFromDataBase.get(i).get(2);
	            	 getlist.add(concat);*/
	            	// dataFromDataBase.add(dataFromDataBase.get(i).get(3));
	            	 //dataFromDataBase.add(dataFromDataBase.get(i).get(2));
	            	
	            // this.aa.notifyDataSetChanged();	
	            // 	             }
			
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		handler.sendEmptyMessage(0);
		
		Looper.loop();

	}




	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			pd.dismiss();
			// Toast.makeText(getApplicationContext(),finalResult, Toast.LENGTH_SHORT).show();
			//                    if(.equals("Logged In Successfully"))
			//                    {
			//                    	
			//                    }

			return;
		}
	};



	
	public void onClick(View v) {
		//need to take faxid associted to row
//		for(int j=0;j<dataFromDataBase.size();j++)
//		{
//			if(v==tr[j])
//			{
//				Toast.makeText(getApplicationContext(),"Fax Id ="+dataFromDataBase.get(j).get(0), Toast.LENGTH_SHORT).show();
//				
//			}
//		}
		
	}



	public InputStream doSubmit(String url, HashMap <String,String> data)throws Exception{


		try{

			URL siteUrl= new URL(url);
			HttpURLConnection conn= (HttpURLConnection)siteUrl.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			DataOutputStream dataOutputStream=new DataOutputStream(conn.getOutputStream());

			Set keys=data.keySet();
			Iterator iter= keys.iterator();
			String content="";
			for(int m=0;iter.hasNext();m++){
				Object key=iter.next();
				if(m!=0)
				{
					content +="&";
				}
				content +=key+"="+URLEncoder.encode(data.get(key),"UTF-8");
			}


			dataOutputStream.writeBytes(content);
			dataOutputStream.flush();
			dataOutputStream.close();

			/*
	BufferedReader bufferedReader= new BufferedReader(new InputStreamReader (conn.getInputStream()));
	String line="";
	String retLine = "";
	while ((line=bufferedReader.readLine())!= null){
		System.out.println(line);
		retLine = retLine + line;
	}

	bufferedReader.close();*/
			return conn.getInputStream();

		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}



}